<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Routing\Controller;
use App\Traits\HttpResponse;
use Laoha\Blog\Transformers\LaohaBlogTransformer;

class AppBaseController extends Controller
{
    use HttpResponse;

	protected $request;

    protected $appName;

	protected $app;

    protected $model;

    protected $service;

    protected $queryBuilder;

    protected $export;

    public function __construct(Request $request)
    {
        $this->request = $request;
		
		$app_name = strtolower($request->route('app'));
		$this->app = get_app($app_name);
        $this->appName = Str::studly($app_name);  
		$this->model = $this->getModel();
    }

    public function index()
    {
        /*
		if ($this->request->has('page')) {
            $dataset = $this->queryBuilder->paginate();
            return response()->json([
                'pagination' => array_except($dataset, 'data'),
                'data' => $dataset['data'],
            ]);
        }*/
		$data = $this->model->with('cate')->get();
		return responder()->success($data,\Laoha\Blog\Transformers\LaohaBlogTransformer::class)->meta(['count' => $this->model->count(),'ss'=>'bb'])->respond();
        //return $this->ok($data,LaohaBlogTransformer::class);
    }

    public function create()
    {
        return response()->json(['data' => $this->service->create($this->request->all())]);
    }

    public function delete($id)
    {
        $this->service->delete($id);

        return response()->json();
    }

    public function show($id)
    {
        return response()->json(['data' => $this->queryBuilder->findOrFail($id)]);
    }


    public function update($id)
    {
        $model = $this->service->update($id, $this->request->all());

        return response()->json(['data' => $model]);
    }

    public function export()
    {
        return $this->export->download();
    }

    protected function getService()
    {
        $serviceName = 'App\Services\\'.$this->appName.'Service';

        if (! class_exists($serviceName)) {
            return new BaseService($this->model);
        }

        return new $serviceName($this->model);
    }

    protected function getModel()
    {
        $model = '\\Laoha\\Blog\\Models\\'.$this->appName;

        if (! class_exists($model)) {
            return resolve('\\App\\Models\\'.$this->appName);
        }

        return resolve($model);
    }

    protected function getExport()
    {
        $exportName = 'App\Exports\\'.$this->appName.'Export';

        if (! class_exists($exportName)) {
            return new BaseExport($this->queryBuilder->getQuery(), $this->request->type);
        }

        return new $exportName($this->model);
    }
}
